package com.lostad.app.core.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lostad.app.core.domain.AppUser;
import com.lostad.app.core.service.AppUserService;

@Controller
@RequestMapping("/main")
public class MainController {

    @Autowired
    private AppUserService AppUserService;

    @GetMapping("/")
    public String home(HttpServletRequest request){
        request.setAttribute("mode", "MODE_HOME");
        return "main";
    }

    @GetMapping(value = "/all")
    public String allAppUsers(HttpServletRequest request){
        request.setAttribute("AppUsers", AppUserService.findAll());
        request.setAttribute("mode", "MODE_AppUserS");
        return "index";
    }

    @GetMapping("/new")
    public String newAppUser(HttpServletRequest request){
        request.setAttribute("mode", "MODE_NEW");
        return "index";
    }
    @PostMapping(value="/save")
    public String saveAppUser(@ModelAttribute AppUser AppUser, BindingResult bindingResult, HttpServletRequest request){
        AppUserService.save(AppUser);
        request.setAttribute("AppUsers", AppUserService.findAll());
        request.setAttribute("mode", "MODE_AppUserS");
        return "index";
    }

    @GetMapping("/update")
    public String updateAppUser(@RequestParam String id, HttpServletRequest request){
        request.setAttribute("AppUser", AppUserService.findAppUser(id));
        request.setAttribute("mode", "MODE_UPDATE");
        return "index";
    }

    @GetMapping(value = "/delete")
    public String delete(@RequestParam String id, HttpServletRequest request) {
        AppUserService.delete(id);
        request.setAttribute("AppUsers", AppUserService.findAll());
        request.setAttribute("mode", "MODE_AppUserS");
        return "index";
    }
}
